from django.shortcuts import render, redirect, HttpResponse

# Create your views here.
from django.core.paginator import Paginator
from django.db.models import Q
from django.urls import reverse
from steed_admin.base_admin import site
from steed_admin.forms import create_model_form


def demo(request):
    """navbar的模板页面"""
    return render(request, 'steed_admin/navbar_demo.html')


def app_index(request):
    """Steed Admin 的首页
    返回所有注册的model
    """
    return render(request, 'steed_admin/app_index.html', {'site': site})


def table_index(request, app_label, model_name):
    """将选择的一张表输出到到页面"""
    admin_obj = site.registered_sites[app_label]['registers'][model_name]
    action_msg = None
    if request.method == 'POST':
        action = request.POST.get('action')
        select_ids = request.POST.getlist('select_ids')
        select_objs = admin_obj.model.objects.filter(id__in=select_ids)
        if action and select_ids:
            action_msg = ('text-success', '执行成功')
            if hasattr(admin_obj, action):
                action_func = getattr(admin_obj, action)
                res = action_func(request, select_objs)
                if isinstance(res, tuple):
                    action_msg = res
                elif isinstance(res, str):
                    action_msg = ('text-success', res)
                elif isinstance(res, HttpResponse):
                    return res
            else:
                action_msg = ('text-danger', '未找到该方法：%s' % action)
        else:
            action_msg = ('text-danger', '未执行任何操作')
    # 过滤
    filter_dic = {}
    for k in admin_obj.list_filter:
        if k in request.GET:
            filter_dic[k] = request.GET.get(k)
    objs = admin_obj.model.objects.filter(**filter_dic)
    # 搜索
    search_key = request.GET.get('search')
    if search_key:
        q_obj = Q()
        q_obj.connector = 'OR'
        for column in admin_obj.search_fields:
            q_obj.children.append(('%s__contains' % column, search_key))
        objs = objs.filter(q_obj)
    # 排序
    order_keys = []
    order_key = request.GET.get('o')
    if order_key:
        order_list = order_key.split('.')
        for order in order_list:
            try:
                order_int = int(order)
                order_index = abs(order_int) - 1
                order_str = admin_obj.list_display[order_index]
            except Exception as e:
                continue
            order_keys.append('%s%s' % (('-' if order.startswith('-') else ''), order_str))
    order_keys = order_keys or ['-id']
    objs = objs.order_by(*order_keys)
    # 分页
    paginator = Paginator(objs, admin_obj.list_per_page)
    page = request.GET.get('page')
    objs = paginator.get_page(page)
    return render(request, 'steed_admin/table_index.html',
                  {'admin_obj': admin_obj, 'objs': objs, 'action_msg': action_msg})


def table_change(request, app_label, model_name, obj_id):
    """修改页面"""
    admin_obj = site.registered_sites[app_label]['registers'][model_name]
    model_form = create_model_form(admin_obj)
    obj = admin_obj.model.objects.get(id=obj_id)
    if request.method == 'POST':
        form_obj = model_form(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect(reverse('steed_admin:table_index', args=(app_label, model_name)))
    else:
        form_obj = model_form(instance=obj)
    return render(request, 'steed_admin/table_change.html', {'admin_obj': admin_obj, 'form_obj': form_obj})


def table_add(request, app_label, model_name):
    """添加页面"""
    admin_obj = site.registered_sites[app_label]['registers'][model_name]
    model_form = create_model_form(admin_obj)
    if request.method == 'POST':
        form_obj = model_form(request.POST)
        if form_obj.is_valid():
            obj = form_obj.save()
            if '_addanother' in request.POST:
                form_obj = model_form()
            elif '_continue' in request.POST:
                return redirect(reverse('steed_admin:table_change', args=(app_label, model_name, obj.id)))
            else:
                return redirect(reverse('steed_admin:table_index', args=(app_label, model_name)))
    else:
        form_obj = model_form()
    return render(request, 'steed_admin/table_add.html', {'admin_obj': admin_obj, 'form_obj': form_obj})


def table_delete(request, app_label, model_name, obj_id):
    """删除确认页面"""
    admin_obj = site.registered_sites[app_label]['registers'][model_name]
    objs = admin_obj.model.objects.filter(id=obj_id)
    if request.method == 'POST':
        objs[0].delete()
        return redirect(reverse('steed_admin:table_index', args=(app_label, model_name)))
    return render(request, 'steed_admin/table_del_confirm.html', {'admin_obj': admin_obj, 'objs': objs})


# 批量删除就单独写一个吧，这样可以和单个删除分开做权限
def table_delete_objs(request, app_label, model_name):
    """批量删除"""
    admin_obj = site.registered_sites[app_label]['registers'][model_name]
    del_ids = request.POST.getlist('del_ids')
    objs = admin_obj.model.objects.filter(id__in=del_ids)
    if request.method == 'POST':
        objs.delete()
        return redirect(reverse('steed_admin:table_index', args=(app_label, model_name)))
    # 下面这个url是有效的，虽然没提供链接，但是可以手动输入url进来。进去后是删除0个
    return render(request, 'steed_admin/table_del_confirm.html', {'admin_obj': admin_obj, 'objs': objs})


